﻿using System;
using System.Web.Caching;
using System.Web;

namespace Mysoft.Platform.Component.Caches
{
	internal class DotnetCache : ICachable
	{
		private readonly Cache _cache = HttpContext.Current.Cache;

		public void Insert(string key, object obj, DateTime absoluteTime, TimeSpan span)
		{
			if( absoluteTime < DateTime.Now || (span == TimeSpan.FromSeconds(0)))
			{
				_cache.Insert(key, obj, null);
			}
			else
			{
				_cache.Insert(key, obj, null, absoluteTime, span);				
			}
		}

		public void Remove(string key)
		{
			_cache.Remove(key);
		}

		public void Update(string key, object obj)
		{
		}

		public T Get<T>(string key)
		{
			try
			{
				object obj = _cache.Get(key);
				if( obj == null ) {
					return default(T);
				}
				return (T)obj;
			}
			catch (Exception)
			{
				return default(T);
			}
		}
	}
}